import {
  Component, OnInit, ViewEncapsulation, ChangeDetectionStrategy, ElementRef, Renderer,
  NgZone, OnDestroy
} from '@angular/core';
import {EventsService} from "@core/events/events.service";

@Component({
  selector: 'seed-progress-bar',
  templateUrl: './progress-bar.component.html',
  styleUrls: ['./progress-bar.component.scss'],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProgressBarComponent implements OnInit, OnDestroy {
  private interval;
  private increase = 0;
  private progressState: Boolean = false;

  constructor(public ele: ElementRef,
              private renderer: Renderer,
              private events: EventsService) {
    this.events.subscribe('request:start', () => {
      this.showProgressBar();
    });
    this.events.subscribe('request:finished', () => {
      this.hideProgressBar();
    });
  }

  ngOnInit() {

  }

  ngOnDestroy() {
    clearInterval(this.interval);
  }

  showProgressBar() {
    const that = this;
    if (!this.progressState) {
      this.progressState = true;
      that.renderer.setElementStyle(
        that.ele.nativeElement.children[0],
        'opacity',
        '1'
      );
      this.interval = setInterval(() => {
        that.increase++;
        that.renderer.setElementStyle(
          that.ele.nativeElement.children[0],
          'width',
          `${that.increase}%`
        );

        if (that.increase === 70) {
          clearInterval(that.interval);
        }
      }, 100);
    }
  }

  hideProgressBar() {
    this.progressState = false;
    const that = this;
    (function () {
      return new Promise((resolve, reject) => {
        that.increase = 0;
        that.renderer.setElementStyle(
          that.ele.nativeElement.children[0],
          'width',
          `100%`
        );
        resolve();
      });
    })().then(() => {
      clearInterval(that.interval);
      setTimeout(() => {
        that.renderer.setElementStyle(
          that.ele.nativeElement.children[0],
          'opacity',
          '0'
        );
        that.renderer.setElementStyle(
          that.ele.nativeElement.children[0],
          'width',
          '0%'
        );
      }, 500);
    });
  }

}
